package com.academy.student;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;

import com.academy.teacher.QuestionAdapter;
import com.academy.teacher.QuestionDetail;
import com.academy.teacher.ReplyToStudentQueries;
import com.academy.teacher.TeacherTabActivity;
import com.academy.teacher.ViewQuestionActivity;
import com.academy.util.AcademyUtility;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class AnswerListActivity extends Activity implements ResponseListener
{
	
	
	
	String message, title;
	String strQuestion,strAnswer,strPostedID,strAnsweredBy,strFileContent;
	
	
	private ArrayList<QuestionDetail> questionDetailsList;
	ListView lvViewQuestion;
	QuestionDetail questionDetail;
	Timer  timer ;
	TimerTask task;
	
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.answer_layout);
        initializeViews();
        
    }
    
    @Override
    protected void onResume() 
    {
    	// TODO Auto-generated method stub
    	super.onResume();
    	questionDetailsList.clear();
    	
    	getListofQuestions(true);
    	
    }

    
    public void initializeViews()
    {
    	lvViewQuestion=(ListView) findViewById(R.id.listView1);
    	questionDetailsList=new ArrayList<QuestionDetail>();
    }
    
    public void getListofQuestions(boolean progrss)
    {				
    	BaseService service  = new BaseService(this, this, RequestMethod.GET);  
    	if(!progrss)
    		service.isProgressAvailable = false;
    	service.addParam(getString(R.string.StudentID_param), AcademyUtility.getStudentID());
    	service.addParam(getString(R.string.userType_Param),"AnswaredQuery");
    	service.execute(getString(R.string.viewAnsweredURL));								
	}
    
    


private void parseResponse(String response)
{
	if(response==null ||response.equals("null"))
	{
		System.out.println("Response ---> "+response);
				
		showAlert(null, "No Server Found!");
	}
	else
	{
		try 
		{ 
			questionDetailsList.clear();
		
			JSONObject RootObject = new JSONObject(response);
			System.out.println("JSON Object==> "+RootObject.toString());
			JSONObject studentPostObject = RootObject.getJSONObject("studentPost");
			
			String strStatus=studentPostObject.getString("status");
			
			if(strStatus.equals("true"))
			{	
				int noOfRows=Integer.parseInt(studentPostObject.getString("noOfRows"));
				if(noOfRows==1)
				{
					JSONObject singleObject=studentPostObject.getJSONObject("studentPostData");
					strQuestion=singleObject.getString("question");
					strAnswer=singleObject.getString("answer");
					strPostedID=singleObject.getString("postID");
					strAnsweredBy=singleObject.getString("teacherID");
					
//					System.out.println("strQuestion="+strQuestion);
					questionDetail=new QuestionDetail();
					questionDetail.setQuestion(strQuestion);
					questionDetail.setAnswer(strAnswer);
					questionDetail.setPostedID(strPostedID);
					questionDetail.setAnsweredBy(strAnsweredBy);
					questionDetailsList.add(questionDetail);
//					System.out.println("questionDetailsList"+questionDetailsList);
				}
				else if(noOfRows>1)
				{
					JSONArray studentPostArray=studentPostObject.getJSONArray("studentPostData");
//					System.out.println("studentPostArray="+studentPostArray);
					int length=studentPostArray.length();
//					System.out.println("length count="+length);
					
	//				JSONObject studentPostDataObject;
	//				noOfRows
					for(int m=0;m<length;m++)
					{
						JSONObject studentPostDataObject=studentPostArray.getJSONObject(m);
//						System.out.println("studentPostDataObject="+studentPostDataObject);
						strQuestion=studentPostDataObject.getString("question");
						strAnswer=studentPostDataObject.getString("answer");
						strPostedID=studentPostDataObject.getString("postID");
						strAnsweredBy=studentPostDataObject.getString("teacherID");
						strFileContent=studentPostDataObject.getString("fileContent");
						
						
//						System.out.println("strQuestion="+strQuestion);
						questionDetail=new QuestionDetail();
						questionDetail.setQuestion(strQuestion);
						questionDetail.setAnswer(strAnswer);
						questionDetail.setPostedID(strPostedID);
						questionDetail.setAnsweredBy(strAnsweredBy);
						questionDetail.setFileContent(strFileContent);
						questionDetailsList.add(questionDetail);
//						System.out.println("questionDetailsList"+questionDetailsList);
					}
				}
//				System.out.println("questionDetailsList sancmn="+questionDetailsList);
				setAdapterForQuestionDetailList();
				
//				showAlert(null, "post in");
//				AcademyUtility.setName(studentData.getString("studentName"));
//				AcademyUtility.setCollegeName(studentData.getString("collageName"));
//				AcademyUtility.setCoarse(studentData.getString("course"));
//				AcademyUtility.setEmailID(studentData.getString("emailID"));
//				AcademyUtility.setStudentID(strUserName);
//				Intent ii=new Intent(this,QueryTabActivity.class);
//				startActivity(ii);
			}
			else if(strStatus.equals("false"))
			{	
				JSONObject studentPostDataObject= studentPostObject.getJSONObject("studentPostData");
				String strError= studentPostDataObject.getString("errorDesc");
				showAlertFalse(null, strError);
			}
		}
		catch (JSONException e) 
		{
			e.printStackTrace();
		} 
	}
}

	public void showAlert(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
//				Intent i=new Intent(StudentActivity.this,Homepage.class);
//				startActivity(i);
//				finish();
				
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}
	
	public void showAlertFalse(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
				Intent i=new Intent(AnswerListActivity.this,TeacherTabActivity.class);
				startActivity(i);
				finish();				
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}

	public void setAdapterForQuestionDetailList()
	{
		lvViewQuestion.setAdapter(new AnswerAdapter(getApplicationContext(), R.layout.answer_list_item, questionDetailsList, this));
		
		sendContinousRequest();
		
		
		
	}
	
	private void sendContinousRequest() {
		if(timer != null)
		{
			timer.cancel();
			timer.purge();
		}
		
		timer = new Timer();
    	task = new TimerTask() {
		
		@Override
		public void run() {
			getListofQuestions(false);
			
		}
    	};
		
		timer.schedule(task, 1000, 30000);
		
	}


	public void passIntentToAnswerActivity(int postion)
	{
		if(timer != null) 
		 {
			System.out.println("pass intent");
			 timer.cancel();
			 timer.purge();
			 timer = null;
		 }
		QuestionDetail selectedQuestionDetail = questionDetailsList.get(postion);
		Intent ii =new Intent(this,AnswerActivity.class);
		ii.putExtra("strPostedID", selectedQuestionDetail.getPostedID());
		ii.putExtra("strQuestion", selectedQuestionDetail.getQuestion());
		ii.putExtra("strAnswer", selectedQuestionDetail.getAnswer());
		ii.putExtra("strAnsweredBy", selectedQuestionDetail.getAnsweredBy());
		ii.putExtra("strFileContent", selectedQuestionDetail.getFileContent());
		startActivity(ii);
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}

 @Override
protected void onDestroy() 
 {
	 System.out.println("Destroy called");
	// TODO Auto-generated method stub
	 if(timer != null) 
	 {
		 System.out.println("timer cancelled");
		 timer.cancel();
		 timer.purge();
		 timer = null;
	 }
	 super.onDestroy();
}
 
}